package org.layui.shop.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.Part;
import org.layui.shop.entity.User;
import org.layui.shop.util.FileUploadUtil;

import java.io.File;
import java.io.IOException;

/**
 * 上传头像 - 使用上传工具上传
 *
 * @author ZQX
 * @date 2024-12-03
 */
@WebServlet("/upload_head_util.do")
@MultipartConfig
public class UploadHead4UtilServlet extends BaseController {
    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        // 1.获取表单中输入的数据
        Part part = req.getPart("head_img");

        // 2.获取项目物理路径
        ServletContext servletContext = req.getServletContext();
        String realPath = servletContext.getRealPath("/images/head/");

        // 3.实例化上传工具对象，并初始化信息
        FileUploadUtil util = new FileUploadUtil();
        util.setAllowFileExt("jpg,png,gif");
        // 单位：byte - 这里是200KB
        util.setMaxSize(200 * 1024);

        // 4.上传头像，返回上传后的文件名
        String filename = util.upload(part, realPath);
        // Service - DAO 处理...(略)
        // 响应结果 - code(0)
        print(res, success(0, filename, "success"));
    }
}
